﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using NewFormatProject.Infrastructure.Atrributes;
using NewFormatProject.Infrastructure.Dto.Responses;
using NewFormatProject.Infrastructure.EFCore;
using NewFormatProject.Server.Interfaces;
using System;
using System.IO;
using System.Reflection;

namespace NewFormatProject.Api.Admin.Filters
{
    public class ActionLogFilter : ActionFilterAttribute
    {
        private readonly IActionLogServer _actionLogServer;
        public ActionLogFilter(IActionLogServer actionLogServer)
        {
            _actionLogServer = actionLogServer;
        }
        public override async void OnResultExecuting(ResultExecutingContext context)
        {
            // 代码在结果执行之前执行

            // 检查是否包含数据
            var result = ((ObjectResult)context.Result)?.Value;
            if (result == null)
                return;
            // 检查控制器方法是否包含指定特性
            var action = context.ActionDescriptor as ControllerActionDescriptor;
            var attr = action.MethodInfo.GetCustomAttribute<ActionLogAttribute>();
            if (attr == null)
                return;//无需记录
                       // 获取 HttpContext
            var message = attr.Message;

            var httpContext = context.HttpContext;
            // 获取请求参数
            string requestParames = "";
            foreach (var key in httpContext.Request.Query.Keys)
            {
                requestParames += key + "=" + httpContext.Request.Query[key] + "&";
            }

            // 如果需要获取表单数据或 JSON 数据
            if (httpContext.Request.HasFormContentType)
            {
                var formCollection = httpContext.Request.Form;
                // 使用 formCollection 获取表单数据
                foreach (var key in formCollection.Keys)
                {
                    requestParames += key + "=" + formCollection[key] + "&";
                }
            }
            else if (httpContext.Request.ContentType.StartsWith("application/json"))
            {
                // 读取 JSON 请求体
                var requestBody = httpContext.Request.Body;
                requestBody.Position = 0;
                using (var reader = new StreamReader(requestBody))
                {
                    var bodyText = await reader.ReadToEndAsync();
                    requestParames += bodyText;
                }
            }

            // 确保 context.HttpContext.User 不为空
            if (context.HttpContext.User == null ||!context.HttpContext.User.Identity.IsAuthenticated)
            {
                return;
            }
            // 假设我们想要读取用户的用户编号
            int uid =Convert.ToInt32(context.HttpContext.User.FindFirst("UId")?.Value);
            // 受影响的行数
            ResponseApiDto responseApiDto = result as ResponseApiDto;
             _actionLogServer.Add(new ActionLogs
            {
                AlRequestParams = requestParames,
                AlIp = context.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "",
                AlRequestMethod = httpContext.Request.Method,
                AlAffectedRows = responseApiDto?.affectedRows??0,
                AlRequestUrl = context.HttpContext.Request.Scheme + "://" + context.HttpContext.Request.Host + context.HttpContext.Request.Path,
                AlUserId = uid,
                AlMessage=message
            });
        }
    }
}

